<template>
  <PageWrapper>
    <a-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @advanced="actionRef.redoHeight()" />
    </a-card>
    <a-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        row-key="id"
        :row-selection="rowSelection"
        ref="actionRef"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <template #tableTitle>
          <a-space>
            <a-button
              type="primary"
              v-permission="{ action: ['business:record:add'] }"
              @click="modalHandle(ModalType.ADD)"
            >
              <template #icon>
                <PlusOutlined class="arco-icon" />
              </template>
              新建
            </a-button>
            <a-button
              type="primary"
              v-permission="{ action: ['business:record:zs'] }"
              @click="transferZsHandle"
            >
              <template #icon>
                <SwapOutlined class="arco-icon" />
              </template>
              转移招商
            </a-button>
            <a-button
              type="primary"
              v-permission="{ action: ['business:record:yy'] }"
              @click="transferYyHandle"
            >
              <template #icon>
                <SwapOutlined class="arco-icon" />
              </template>
              转移运营
            </a-button>
          </a-space>
        </template>
        <template #index="scoped">
          {{ scoped.rowIndex + 1 }}
        </template>
        <template #actions="{ record }">
          <a-button
            style="margin: 0 10px"
            type="primary"
            size="mini"
            @click="modalHandle(ModalType.EDIT, record)"
            v-permission="{ action: ['business:record:edit'] }"
          >
            编辑
          </a-button>
          <a-button
            style="margin: 0 10px"
            type="primary"
            size="mini"
            @click="modalHandle(ModalType.VIEW, record)"
            v-permission="{ action: ['business:record:view'] }"
          >
            查看
          </a-button>
          <a-dropdown :popup-max-height="false">
            <a-button style="margin: 0 10px" type="primary" size="mini">
              更多
              <icon-down />
            </a-button>
            <template #content>
              <a-doption
                v-permission="{ action: ['business:record:download-img'] }"
                @click="downloadImages(record)"
              >
                一键下载图片
              </a-doption>
              <a-doption
                v-permission="{ action: ['business:record:record'] }"
                @click="dealRecords(record)"
              >
                操作记录
              </a-doption>
            </template>
          </a-dropdown>
        </template>
        <template #toolbar>
          <a-button type="primary" @click="actionRef.reload()">刷新数据</a-button>
        </template>
      </BasicTable>
    </a-card>
    <CreateModal ref="createModalRef" @submit="reloadTable" />
    <TransferZs ref="transferZsRef" @submit="reloadTable" />
    <TransferYy ref="transferYyRef" @submit="reloadTable" />
    <RecordList ref="recordListRef" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import { ModalType } from '@/enums/permissionsEnum';
  import { type FormSchema, BasicForm, useForm } from '@/components/Form/index';
  import { COOPERATION_PLATFORM_OPTIONS } from '@/constants/business';
  import { useDept } from '@/hooks/system/useDept';
  import { BasicColumn, BasicTable } from '@/components/Table';
  import { PlusOutlined, SwapOutlined } from '@vicons/antd';
  import { getBusinessRecordList } from '@/api/business/record-management';
  import CreateModal from './CreateModal.vue';
  import TransferZs from './TransferZs.vue';
  import TransferYy from './TransferYy.vue';
  import RecordList from './record-list.vue';
  import { Message } from '@arco-design/web-vue';
  import { getUserList } from '@/api/system/user';
  import { ComputedRef, Ref } from 'vue';
  import { useGlobSetting } from '@/hooks/setting';
  // import { useRouter } from 'vue-router';
  // const router = useRouter();
  const globSetting = useGlobSetting();

  const actionRef = ref();
  const createModalRef = ref();

  const { deptMap } = useDept({ deptNames: ['招商部', '运营部'] });
  const attractManOptions = ref<any[]>([]);
  const operatorOptions = ref<any[]>([]);
  const schemas: ComputedRef<FormSchema[]> = computed(() => {
    return [
      {
        field: 'poiId',
        component: 'Input',
        label: '门店ID',
        componentProps: {
          allowClear: true,
        },
      },
      {
        field: 'poiName',
        component: 'Input',
        label: '门店名称',
        componentProps: {
          allowClear: true,
        },
      },
      {
        field: 'hezuopingt',
        component: 'Select',
        label: '合作平台',
        componentProps: {
          allowClear: true,
          placeholder: '请选择合作平台',
          options: COOPERATION_PLATFORM_OPTIONS,
        },
      },
      {
        field: 'attractManDept',
        component: 'Select',
        label: '招商部',
        wrapperColStyle: { width: '100%' },
        componentProps: {
          clearable: true,
          placeholder: '请选择所属招商',
          options: deptMap['招商部'].children,
          // 'allow-clear': true,
          'field-names': {
            label: 'deptName',
            value: 'deptId',
          },
          onChange: (deptId: string) => {
            loadUserList(deptId, attractManOptions);
          },
        },
      },
      {
        field: 'attractManId',
        component: 'Select',
        label: '招商人员',
        wrapperColStyle: { width: '100%' },

        componentProps: {
          clearable: true,
          placeholder: '请选择招商人员',
          options: attractManOptions.value,
          'allow-clear': true,
          'field-names': {
            label: 'nickname',
            value: 'userId',
          },
        },
      },
      {
        field: 'operateDept',
        component: 'Select',
        label: '所属运营',
        wrapperColStyle: { width: '100%' },
        componentProps: {
          clearable: true,
          placeholder: '请选择所属运营',
          'allow-clear': true,
          options: deptMap['运营部'].children,
          'field-names': {
            label: 'deptName',
            value: 'deptId',
          },
          onChange: (deptId: string) => {
            loadUserList(deptId, operatorOptions);
          },
        },
      },
      {
        field: 'operator',
        component: 'Select',
        label: '运营人员',
        wrapperColStyle: { width: '100%' },
        componentProps: {
          clearable: true,
          'allow-clear': true,
          placeholder: '请选择运营人员',
          options: operatorOptions.value,
          'field-names': {
            label: 'nickname',
            value: 'userId',
          },
        },
      },
    ];
  });

  const [register, { setSchema }] = useForm({
    labelColProps: {
      span: 6,
    },
    wrapperColProps: {
      span: 18,
    },
    labelWidth: 90,
    layout: 'inline',
    rowProps: { gutter: [8, 8] },
    colProps: {
      xs: 24,
      sm: 24,
      md: 12,
      lg: 8,
      xl: 6,
    },
    schemas: schemas.value,
  });
  function loadUserList(deptId: string, options: Ref<any[]>) {
    options.value = [];
    if (!deptId) return;
    getUserList({ deptId, pageSize: 99999, page: 1 }).then((res) => {
      options.value = res.list;
      setSchema(schemas.value);
    });
  }
  function handleSubmit(values: Recordable) {
    if (values) {
      actionRef.value.reload(values);
    }
  }
  const columns: BasicColumn[] = [
    {
      title: '序号',
      slotName: 'index',
      width: 70,
    },
    {
      title: '门店ID',
      dataIndex: 'uuid',
      width: 300,
    },
    {
      title: '门店名称',
      dataIndex: 'poiName',
      width: 300,
    },
    {
      title: '合作平台',
      dataIndex: 'plantform',
      width: 200,
    },
    {
      title: '所属招商',
      dataIndex: 'attractManDeptName',
      width: 200,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 120,
    },
    {
      title: '创建日期',
      width: 200,
      dataIndex: 'createDate',
    },
    {
      title: '操作',
      width: 254,
      slotName: 'actions',
      fixed: 'right',
    },
  ];
  const loadDataTable = async (res) => {
    const { pageSize, page } = res;
    const response = await getBusinessRecordList({ ...res, pageSize: pageSize, pageNum: page });
    return {
      totalCount: response.totalCount,
      list: response.list,
    };
  };
  const reloadTable = () => {
    actionRef.value.reload();
  };

  const rowKeys = ref([]);
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  function handleSelect(keys) {
    rowKeys.value = keys;
  }

  function handleSelectAll(checked) {
    rowKeys.value = checked ? actionRef.value.getDataSource().map((item) => item.id) : [];
  }

  function modalHandle(modalType: ModalType, record?: Recordable) {
    createModalRef.value.openModal(modalType, record);
  }
  const transferZsRef = ref();
  const transferYyRef = ref();
  const recordListRef = ref();
  function transferZsHandle() {
    if (rowKeys.value.length < 1) {
      return Message.warning('请选择商户');
    }
    transferZsRef.value.openModal(rowKeys.value);
  }
  function transferYyHandle() {
    if (rowKeys.value.length < 1) {
      return Message.warning('请选择商户');
    }
    transferYyRef.value.openModal(rowKeys.value);
  }

  function downloadImages(row) {
    try {
      const { apiUrl, urlPrefix1 } = globSetting;
      location.href = `${apiUrl}${urlPrefix1}/merchantData/downMerchantData/${row.uuid}`;
    } catch (error) {
      console.log(error);
    }
  }
  function dealRecords(record: Recordable) {
    recordListRef.value.openModal(record.id);
    // router.push({
    //   path: `business/record-management/record-list`,
    //   query: {
    //     merchantDataId: record.id,
    //   },
    // });
  }
</script>

<style lang="less" scoped>
  :deep(.arco-picker) {
    width: 100% !important;
  }
</style>
